using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Threading;
using Microsoft.SharePoint.Client;
using MSDN.Samples.ClaimsAuth;


namespace SPSDll
{
    public partial class SPMain : System.Windows.Forms.Form
    {
        string strCroppedFilePath = null;
        private Image pbImage;
        protected DataTable dtDemo = null;
        string strSiteURL = "";
        string strSiteName = "";
        private ArrayList threadList = new ArrayList();
        private ArrayList summeryList = new ArrayList();
        Hashtable hTable_Attachments = new Hashtable();
        private TreeNode _treeNode;
        private TreeNode m_OldSelectNode;

        #region Properties
        public TreeNode TreeNode
        {
            get { return _treeNode; }
            set { _treeNode = value; }
        }
        #endregion

        #region SPMain CTR
        public SPMain()
        {
            InitializeComponent();

        }
        public SPMain(string strFilePath)
        {
            InitializeComponent();

            strCroppedFilePath = strFilePath;
            pbImage = Image.FromFile(strFilePath);
            this.pictureBox1.Image = pbImage;

            //Image image = Image.FromFile(strCroppedFilePath);
            //pictureBox1.Image = Image.FromFile("C:\\Users\\bhanu\\Desktop\\Cropper\\Cropper Capture[5].jpeg");
            //pictureBox1.Image = new Bitmap(strFilePath);
            //pictureBox1.Load(strFilePath);
        }
        #endregion

        #region Thread
        private void BeginProcess(object path)
        {
            try
            {
                Process.Start((string)path);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
        }
        #endregion

        #region Event Handler
        private void rbnBtn_Connect_Click(object sender, EventArgs e)
        {
            strSiteURL = this.cmbSiteUrl.Text;
            //progressbar starts working here
            this.toolStripStatusLabel.Text = "Connected to " + strSiteURL;

            if (progressBar.Value == progressBar.Maximum)
            {
                progressBar.Value = progressBar.Minimum;
            }
            for (int i = progressBar.Minimum; i <= progressBar.Maximum; i++)
            {
                progressBar.PerformStep();
            }
            //FillList_LibraryTree(strSiteName);
            FillDocLibTree(strSiteName, strSiteURL);

        }
        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.toolStripStatusLabel.Text = " Tree Refresh";
            treeDocumentLibrary.Nodes.Clear();
            FillDocLibTree(strSiteName, strSiteURL);
        }
        private void deleteAttachmentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DeleteAttachment())
            {
                this.toolStripStatusLabel.Text = "File Deleted";
                treeDocumentLibrary.Nodes.Clear();
                FillDocLibTree(strSiteName, strSiteURL);
            }

        }
        private void uploadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool check = UploadImage();
            if (check)
            {
                this.toolStripStatusLabel.Text = "Document Uploaded Successfull !!!";
                this.pictureBox1.Image = null;
                this.pictureBox1.Invalidate();
            }
        }
        private void treeView_MouseUp(object sender, MouseEventArgs e)
        {
            // Show menu only if the right mouse button is clicked.
            if (e.Button == MouseButtons.Right)
            {
                // Point where the mouse is clicked.
                Point p = new Point(e.X, e.Y);

                // Get the node that the user has clicked.
                TreeNode node = treeDocumentLibrary.GetNodeAt(p);
                if (node != null)
                {
                    // Select the node the user has clicked.
                    // The node appears selected until the menu is displayed on the screen.
                    m_OldSelectNode = treeDocumentLibrary.SelectedNode;
                    treeDocumentLibrary.SelectedNode = node;
                    contextMenuAttachment.Show(treeDocumentLibrary, p);
                    // Highlight the selected node.
                    treeDocumentLibrary.SelectedNode = m_OldSelectNode;
                    m_OldSelectNode = null;
                }
            }

        }
        private void tv_NodeDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {

            try
            {
                //if (Convert.ToString(this.treeDocumentLibrary.SelectedNode.Parent.Tag) == "List"
                //    || Convert.ToString(this.treeDocumentLibrary.SelectedNode.Parent.Tag) == "Library")
                //    Fill_List_Library_ItemTree(this.treeDocumentLibrary.SelectedNode);

                if (Convert.ToString(this.treeDocumentLibrary.SelectedNode.Tag) == "Item")
                {
                    string strSelectedFilePath = strSiteURL + Convert.ToString(treeDocumentLibrary.SelectedNode.FullPath);
                    //pbImage = Image.FromFile(DisplayAttachment());
                    pbImage = new System.Drawing.Bitmap(new System.IO.MemoryStream(new System.Net.WebClient().DownloadData(DisplayAttachment())));
                    this.pictureBox1.Image = pbImage;
                }

            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                MessageBox.Show(ex.Detail.InnerText);
            }
        }
        #endregion

        private void FillDocLibTree(string strRootSiteName, string strSiteUrl)
        {
            using (ClientContext clientcontext = ClaimClientContext.GetAuthenticatedContext(strSiteURL))
            {
                //Load Libraries from SharePoint
                clientcontext.Load(clientcontext.Web.Lists);
                clientcontext.ExecuteQuery();
                foreach (List list in clientcontext.Web.Lists)
                {
                    try
                    {
                        if (list.BaseType.ToString() == "DocumentLibrary" && !list.IsApplicationList && !list.Hidden && list.Title != "Form Templates" && list.Title != "Customized Reports" && list.Title != "Site Collection Documents" && list.Title != "Site Collection Images" && list.Title != "Images")
                        {
                            clientcontext.Load(list);
                            clientcontext.ExecuteQuery();
                            clientcontext.Load(list.RootFolder);
                            clientcontext.Load(list.RootFolder.Files);
                            clientcontext.ExecuteQuery();
                            treeDocumentLibrary.ImageList = this.imgList_TreeView;
                            treeDocumentLibrary.ShowLines = true;
                            TreeNode LibraryNode = new TreeNode(list.Title);
                            LibraryNode.ImageIndex = 1;
                            LibraryNode.Tag = "Library";
                            treeDocumentLibrary.Nodes.Add(LibraryNode);
                            foreach (Microsoft.SharePoint.Client.File itemFile in list.RootFolder.Files)
                            {
                                //if (itemFile.Name != "Forms")
                                //{
                                TreeNode MainNode = new TreeNode(itemFile.Name);
                                MainNode.ImageIndex = 3;
                                MainNode.Tag = "Item";
                                LibraryNode.Nodes.Add(MainNode);
                                //FillTreeViewNodes(SubFolder, MainNode, clientcontext);
                                //}
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                    }

                }
            }
        }
        //Recursive Function - SubFolders
        //public void FillTreeViewNodes(Folder SubFolder, TreeNode MainNode, ClientContext clientcontext)
        //{
        //    clientcontext.Load(SubFolder.Folders);
        //    clientcontext.ExecuteQuery();
        //    foreach (Folder Fol in SubFolder.Folders)
        //    {
        //        TreeNode SubNode = new TreeNode(Fol.Name);
        //        MainNode.Nodes.Add(SubNode);
        //        FillTreeViewNodes(Fol, SubNode, clientcontext);
        //    }
        //}
        private string DisplayAttachment()
        {
            try
            {
                string strAttachmentFilePath = "";
                string strListName = treeDocumentLibrary.SelectedNode.Parent.Text.ToString();
                string strSelectedItem = treeDocumentLibrary.SelectedNode.Text.ToString();
                using (ClientContext clientcontext = ClaimClientContext.GetAuthenticatedContext(strSiteURL))
                {
                    List list = clientcontext.Web.Lists.GetByTitle(strListName);
                    clientcontext.Load(list);
                    clientcontext.ExecuteQuery();

                    FileCollection files = list.RootFolder.Files;
                    clientcontext.Load(files);
                    clientcontext.ExecuteQuery();
                    foreach (Microsoft.SharePoint.Client.File file in files)
                    {
                        if (file.Name == strSelectedItem)
                        {
                            strAttachmentFilePath = file.ServerRelativeUrl.ToString();
                        }

                    }
                }
                return strAttachmentFilePath;
            }

            catch (Exception ex)
            {
                this.toolStripStatusLabel.Text = ex.Message;
                return null;
            }
        }
        private bool DeleteAttachment()
        {
            bool check = false;
            try
            {
                string strListName = treeDocumentLibrary.SelectedNode.Parent.Text.ToString();
                string strSelectedItem = treeDocumentLibrary.SelectedNode.Text.ToString();
                using (ClientContext clientcontext = ClaimClientContext.GetAuthenticatedContext(strSiteURL))
                {
                    List list = clientcontext.Web.Lists.GetByTitle(strListName);
                    clientcontext.Load(list);
                    clientcontext.ExecuteQuery();

                    FileCollection files = list.RootFolder.Files;
                    clientcontext.Load(files);
                    clientcontext.ExecuteQuery();
                    foreach (Microsoft.SharePoint.Client.File file in files)
                    {
                        if (file.Name == strSelectedItem)
                        {
                            file.DeleteObject();
                            clientcontext.ExecuteQuery();
                            check = true;
                        }

                    }
                }
                return check;
            }

            catch (Exception ex)
            {
                this.toolStripStatusLabel.Text = ex.Message;
                return check;
            }
        }
        private bool UploadImage()
        {
            bool flag = false;
            try
            {
                using (ClientContext context = ClaimClientContext.GetAuthenticatedContext(strSiteURL))
                {
                    Web web = context.Web;
                    FileCreationInformation newFile = new FileCreationInformation();

                    newFile.Content = System.IO.File.ReadAllBytes(strCroppedFilePath);

                    char[] delimiterChars = { '[', ']' };
                    string[] no = strCroppedFilePath.Split(delimiterChars);

                    newFile.Url = "Capture Point" + no[1] + ".jpeg";
                    List docs = web.Lists.GetByTitle(treeDocumentLibrary.SelectedNode.Text);
                    Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
                    context.Load(uploadFile);
                    context.ExecuteQuery();

                }
                flag = true;
                return flag;
            }
            catch (Exception ex)
            {
                return flag;
            }
        }

        //private void FillList_LibraryTree(string strRootSiteName)
        //{
        //    using (ClientContext context = ClaimClientContext.GetAuthenticatedContext(strSiteURL))
        //    {
        //        context.Load(context.Web);
        //        context.Load(context.Web.Lists);
        //        context.ExecuteQuery();

        //        string strSiteTitle = context.Web.Title;

        //        treeDocumentLibrary.ImageList = this.imgList_TreeView;

        //        //TreeNode documentNode = new TreeNode("Document Library");
        //        //documentNode.ImageIndex = 1;
        //        //documentNode.Tag = "Libarary";

        //        TreeNode listNode = new TreeNode("Lists");
        //        listNode.ImageIndex = 1;
        //        listNode.Tag = "List";

        //        TreeNode siteNode = new TreeNode(strSiteTitle);
        //        siteNode.ImageIndex = 0;
        //        siteNode.Tag = "Site";



        //        ListCollection lists = context.Web.Lists;

        //        foreach (List list in lists)
        //        {
        //            listNode.Nodes.Add(list.Title).ImageIndex = 2;
        //            //listNode.ImageIndex = 2;
        //        }

        //        siteNode.Nodes.Add(listNode);
        //        treeDocumentLibrary.Nodes.Add(siteNode);
        //        listNode.ExpandAll();
        //        siteNode.ExpandAll();
        //        treeDocumentLibrary.ExpandAll();
        //    }
        //}
        //private void Fill_List_Library_ItemTree(TreeNode tnList_LibraryNode)
        //{
        //    try
        //    {
        //        TreeNode tnItemNode = new TreeNode();
        //        string strListItem = "";
        //        string strListName = treeDocumentLibrary.SelectedNode.Text.ToString();
        //        if (Convert.ToString(tnList_LibraryNode.Tag) != "Item")
        //        {
        //            using (ClientContext context = ClaimClientContext.GetAuthenticatedContext(strSiteURL))
        //            {

        //                List list = context.Web.Lists.GetByTitle(strListName);

        //                CamlQuery query = new CamlQuery();
        //                query.ViewXml = "<View/>";
        //                ListItemCollection listItems = list.GetItems(query);

        //                context.Load(list);
        //                context.Load(listItems);

        //                context.ExecuteQuery();

        //                foreach (ListItem item in listItems)
        //                {
        //                    strListItem = item.FieldValues["FileLeafRef"].ToString();
        //                    tnList_LibraryNode.Nodes.Add(strListItem).ImageIndex = 3;
        //                    tnList_LibraryNode.Tag = "Item";
        //                }
        //            }
        //        }

        //    }
        //    catch (System.Web.Services.Protocols.SoapException ex)
        //    {
        //        MessageBox.Show(ex.Detail.InnerText);
        //    }
        //}






    }
}